package cn.bintools.daios.example.thrift.server;

import cn.bintools.daios.example.thrift.HelloService;
import cn.bintools.daios.example.thrift.impl.HelloServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.TTransportFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 初始化thrift服务
 *
 * @author <a href="jian.huang@bintools.cn">yunzhe</a>
 * @version 1.0.0 2019-07-02-下午7:10
 */
@Component
@Slf4j
public class ThriftServer {
    @Value("${thrift.port}")
    private int port;

    private TBinaryProtocol.Factory protocolFactory;

    private TTransportFactory transportFactory;



    public void init(){
        protocolFactory = new TBinaryProtocol.Factory();
        transportFactory = new TTransportFactory();
    }

    public void start(){
        // HelloService.Processor<HelloRpcController> processor = new HelloService.Processor<HelloRpcController>(new HelloRpcController());
        TProcessor processor = new HelloService.Processor<HelloService.Iface>(new HelloServiceImpl());
        init();
        try {
            TServerTransport transport = new TServerSocket(port);
            //TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(transport);
            TServer.Args tArgs = new TServer.Args(transport);
            tArgs.processor(processor);
            tArgs.protocolFactory(protocolFactory);
            tArgs.transportFactory(transportFactory);
            /*tArgs.minWorkerThreads(minThreads);
            tArgs.maxWorkerThreads(macThreads);*/
            //多线程 在关闭时多次请求报null异常
            //TServer server = new TThreadPoolServer(tArgs);
            TServer server = new TSimpleServer(tArgs);
            log.info("thrift server start success, port={}",port);
            server.serve();
        } catch (TTransportException e) {
            log.error("thrift server start fail",e);
        }
    }
}    